import fs from 'fs';
import { fileURLToPath, pathToFileURL } from 'url';



//findControllers方法，找到控制器路径
function findControllers() {
    //解析出controller的文件url
    let xDir = new URL('../controllers', import.meta.url);
    let controllerDir = fileURLToPath(xDir);//转换为本地文件系统路径

    //判断文件是否存在
    if (fs.existsSync(controllerDir)) {
        //存在，用同步方法读取所有文件
        let allfile = fs.readdirSync(controllerDir);
        //找到Controller文件后，转换为文件Url
        let allcontrollerfile = allfile.filter(item => item.endsWith('.js')).map(item => pathToFileURL(controllerDir + '/' + item))

        return allcontrollerfile;

    }
    return null;
}


//registerRoute方法，遍历所有Controller文件，注册路由
function registerRoute(router, controllers) {
    if (controllers === null) {
        return
    }

    //遍历控制器文件
    controllers.forEach(async item => {
        //动态导入
        let { obj } = await import(item);

        //遍历模块中的对象
        for (var key in obj) {
            let [keyMethod, keyPath] = key.split(' ');
            let keyFn = obj[key];

            if (keyMethod === 'get') {
                router.get(keyPath, keyFn);
            }
            if (keyMethod === 'post') {
                router.post(keyPath, keyFn);
            }
            if (keyMethod === 'put') {
                router.put(keyPath, keyFn);
            }
            if (keyMethod === 'delete') {
                router.delete(keyPath, keyFn);
            }
        }
    });
}


export const findAllcontroller = findControllers
export const regRoute = registerRoute
